package com.fjec.market.rabbitmq.consumer;

import com.fjec.common.util.DateUtil;
import com.fjec.common.util.SequenceIdGenerator;
import com.fjec.common.ys.protocol.ResRegister;
import com.fjec.market.entity.BizYespayRegLog;
import com.fjec.market.entity.InfoYsepayRegister;
import com.fjec.market.service.IBizYespayRegLogService;
import com.fjec.market.service.IInfoYsepayRegisterService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Component
public class YsRegConsumer {

    @Resource
    private IInfoYsepayRegisterService ysepayRegisterService;

    @Resource
    private SequenceIdGenerator idGenerator;

    @Resource
    private IBizYespayRegLogService bizYespayRegLogService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "${fjec.market.ys.reg.queue.name}",
                            durable = "${fjec.market.ys.reg.queue.durable}"
                    ),
                    exchange = @Exchange(
                            value = "${fjec.market.ys.reg.exchange.name}",
                            durable = "${fjec.market.ys.reg.exchange.durable}",
                            type = "${fjec.market.ys.reg.exchange.type}",
                            ignoreDeclarationExceptions = "${fjec.market.ys.reg.exchange.ignoreDeclarationExceptions}"
                    ),
                    key = "${fjec.market.ys.reg.router.key}"
            )
    )
    @RabbitHandler
    public void onYsReg(@Payload Long ysRegId, Channel channel, @Headers Map<String, Object> headers) throws Exception {
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
//        Long merchantNo = idGenerator.nextId();
        // 修改进件唯一标识
        InfoYsepayRegister entity = ysepayRegisterService.getById(ysRegId);
        // 创建merchantNo = busiType-busiId-updateVer
        StringBuilder sb = new StringBuilder();
        sb.append(entity.getBusiType())
                .append("-")
                .append(entity.getBusiId().toString())
                .append("-")
                .append(entity.getUpdateVer());
        entity.setMerchantNo1(sb.toString());
        ysepayRegisterService.updateById(entity);
        ResRegister resRegister = null;
        try {
            // 进件
            resRegister = ysepayRegisterService.ysReg(ysRegId);
            channel.basicAck(deliveryTag, true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            channel.basicReject(deliveryTag, false);
//            try {
//                // 进件异常，用merchantNo去银盛查询进件结果,成功、失败或不存在：成功写3，失败写4，不存在则依靠进件补偿
//                ysepayRegisterService.searchYsReg(entity.getMerchantNo());
//            } catch (Exception e) {
//                log.error(e.getMessage(), e);
//            }
        }
        recordLog(entity, resRegister);
    }

    private void recordLog(InfoYsepayRegister entity, ResRegister resRegister) {
        // 银盛进件log表
        BizYespayRegLog logEntity = new BizYespayRegLog();
        logEntity.setRegId(entity.getId());
        logEntity.setCustName(entity.getCustName());
        logEntity.setMerchantNo(entity.getMerchantNo1());
        logEntity.setCreateTime(DateUtil.nowLdt());
        logEntity.setOptType(1);
        if (resRegister != null) {
            logEntity.setReturnData(resRegister);
            if (resRegister.getCode() == 10000) {
                logEntity.setUserCode(resRegister.getUserCode());
                logEntity.setCustId(resRegister.getCustId());
                logEntity.setUserStatus(resRegister.getUserStatus());
                logEntity.setRegSuccess(1);
            } else {
                logEntity.setRegSuccess(0);
            }
        }
        bizYespayRegLogService.save(logEntity);
    }
}
